/** 
 * CanvasModel.java
 * @author Lex
 * 2007-8-24 ����09:48:07
 */
package fun.ui.canvas;

import javax.swing.event.EventListenerList;

import fun.symtable.FunctionEntry;
import fun.symtable.SymbolTable;

public class DefaultCanvasModel implements CanvasModel {
	protected Function function = null;
	// ===========================================
	private EventListenerList listenerList = null;

	public DefaultCanvasModel() {
		this.listenerList = new EventListenerList();
	}

	public DefaultCanvasModel(FunctionEntry function) {
		this();
		this.setFunction(function);
	}

	public FunctionEntry getFunction() {
		return this.function;
	}

	public void setFunction(FunctionEntry function) {
		this.function = new Function(function);
		this.fireModelChanged();
	}

	public double getValue(SymbolTable symtable, double argument) {
		if (null == function)
			return 0;
		return this.function.getValue(symtable, argument);
	}

	// event support
	public void addCanvasModelListener(CanvasModelListener l) {
		listenerList.add(CanvasModelListener.class, l);
	}

	public void removeCanvasModelListener(CanvasModelListener l) {
		listenerList.remove(CanvasModelListener.class, l);
	}

	// Notify all listeners that have registered interest for
	// notification on this event type. The event instance
	// is lazily created using the parameters passed into
	// the fire method.
	protected void fireModelChanged() {
		CanvasModelEvent event = null;
		// Guaranteed to return a non-null array
		Object[] listeners = listenerList.getListenerList();
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = listeners.length - 2; i >= 0; i -= 2) {
			if (listeners[i] == CanvasModelListener.class) {
				// Lazily create the event:
				if (event == null)
					event = new CanvasModelEvent(this);
				((CanvasModelListener) listeners[i + 1]).modelChanged(event);
			}
		}
	}
}
